/*
 * Author : Thanh Pham
 * Create : 7:35 , 14/9/2013
 * 
 */
package Bussiness;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import DAO.LoginDAO;
import Entity.Users;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport{
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String username;
    private String password;
    private String rememberLogin;
    private HttpServletRequest request;
    private HttpServletResponse response;
    private HttpSession session;
    
    public String execute(){    	
    	try{
            Users user = new Users();
            user.setUsername(username);
            user.setPassword(password);            
            user = LoginDAO.checkUsers(user);
            
            if(user.getUserId() != 0){
                request = ServletActionContext.getRequest();
                session = request.getSession();
                session.setAttribute("userSession", user);  
                
                if(rememberLogin != null && !rememberLogin.equals("")){
                    Cookie c_u = new Cookie("c_u", user.getUsername());
                    c_u.setMaxAge(300);
                    response = ServletActionContext.getResponse();
                    response.addCookie(c_u);
                }
            	return SUCCESS;
            }else {
                addActionMessage("Invalid username or password.");
                return ERROR;            	
			}
            
    	}catch(Exception ex){
    		addActionMessage("Invalid username or password."+ex.getMessage());
            return ERROR;
    	}
    }
    
    
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getRememberLogin() {
		return rememberLogin;
	}
	public void setRememberLogin(String rememberLogin) {
		this.rememberLogin = rememberLogin;
	}        	
}
